<template>
  <el-dialog
    title="分配权限"
    :visible.sync="dialogVisible"
    width="50%"
    @close="close"
  >
    <el-tree
      ref="tree"
      node-key="id"
      :expand-on-click-node="false"
      default-expand-all
      :data="permissionList"
      show-checkbox
      :default-checked-keys="permIds"
      :props="defaultProps"
      check-strictly
    />
    <el-row slot="footer" type="flex" justify="center">
      <el-col :span="5">
        <el-button size="mini" type="primary" @click="handlePermission">提交</el-button>
        <el-button size="mini" @click="close">取消</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import { getPermissionList } from '@/api/permission'
import { transListToTree } from '@/utils'
import { roleDetail, setPermission } from '@/api/role'
export default {
  components: {},
  data() {
    return {
      id: '',
      dialogVisible: false,
      permissionList: [],
      // 默认选中的key
      permIds: [],
      // 使depts数据映射到组件
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  methods: {
    async open(id) {
      this.id = id
      this.permissionList = transListToTree(await getPermissionList(), 0)
      const res = await roleDetail(id)
      this.permIds = res.permIds
      this.dialogVisible = true
    },
    async handlePermission() {
      // 获取实时选中的数据
      this.permIds = this.$refs.tree.getCheckedKeys()
      await setPermission({
        id: this.id,
        permIds: this.permIds
      })
      this.$message.success('分配权限成功')
      this.close()
    },
    close() {
      this.permIds = []
      this.dialogVisible = false
    }
  }
}
</script>

<style scoped>

</style>
